<template>
	<view>
		<view class="interface" style="margin-top: 100rpx;">
			<text>按1-2进行点击</text>
			<button @click="initBlue">1、初始化蓝牙</button>
			<button @tap="startBluetoothDiscovery">2、开始蓝牙搜索</button>
			<button @click="closeConnection">断开连接</button>
		</view>
	</view>
</template>

<script>
export default {
	name:"blood-pressure-connection",
  data() {
    return {
      bluetoothDevices: [], // 存储蓝牙设备列表
      serviceId: "",
      notifyId: "",
      deviceId: "" ,// 0xFFE0，0xFFE1 0xFFE2
			valueList:[] // 这里的话要对第三个数除10
    };
  },
  methods: {
    // 1. 初始化蓝牙
    initBlue() {
      uni.openBluetoothAdapter({
        success(res) {
          console.log("初始化蓝牙成功");
          console.log(res);
        },
        fail(err) {
          console.log("初始化蓝牙失败");
          console.error(err);
        },
      });
    },
    // 2.1 开启搜寻功能
    startBluetoothDiscovery() {
      uni.startBluetoothDevicesDiscovery({
        success: (res) => {
          console.log("蓝牙搜索已启动", res);
          this.listenBluetoothDevices();
        },
        fail: (err) => {
          console.error("启动蓝牙搜索失败", err);
        },
      });
    },
    // 2.2 监听搜寻到新设备
    listenBluetoothDevices() {
      uni.onBluetoothDeviceFound((res) => {
        const devices = res.devices;
        this.bluetoothDevices.push(...res.devices);
        for (let i = 0; i < devices.length; i++) {
					// TODO 这里需要对筛选出设备来
          console.log(
            "name:" +
              devices[i].name +
              " id: " +
              devices[i].deviceId +
              ", uuid: " +
              devices[i].advertisServiceUUIDs
          );
					if(devices[i].name=="AOJ-30B"){
						this.handleBluetoothDeviceClick(devices[i]);
						break;
					}
        }
      });
    },
    // 3 点击进行蓝牙连接
    handleBluetoothDeviceClick(device) {
      console.log(
        "点击了蓝牙设备" + device.deviceId + " " + device.advertisServiceUUIDs
      );

      this.connectBluetoothDevice(
        device.deviceId,
        device.advertisServiceUUIDs[0]
      ); // 将device.deviceId传递给连接方法
    },
    connectBluetoothDevice(deviceId, serviceUuid) {
      console.log("待连接的设备id为" + deviceId);
      uni.createBLEConnection({
        deviceId: deviceId,
        success: (res) => {
          console.log("蓝牙设备连接成功", res);
          this.deviceId = deviceId;
          this.serviceId = serviceUuid;
          // 断开连接
          this.stopBluetoothDiscovery();
					//  这里开始获取特征值
					this.getCharacteristics();
        },
        fail: (err) => {
          console.error("蓝牙设备连接失败", err);
        },
      });
    },
    stopBluetoothDiscovery() {
      uni.stopBluetoothDevicesDiscovery({
        success: (res) => {
          console.log("蓝牙搜索已停止", res);
          // this.bluetoothDevices = [];
        },
        fail: (err) => {
          console.error("停止蓝牙搜索失败", err);
        },
      });
    },
		notifyDevice(notifyId) {
		  console.log("进入了消息监听，下面是特征值");
		  console.log(notifyId);
		  console.log("正在进行监听数据");
		  uni.notifyBLECharacteristicValueChange({
		    state: true,
		    deviceId: this.deviceId, // 设备ID，在【4】里获取到
		    serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
		    characteristicId: notifyId, // 特征值，在【7】里能获取到
		    success:(res) =>{
					console.log("监听成功")
		      console.log(res);
		      // 接受消息的方法
		      this.listenValueChange();
		    },
		    fail :(err)=> {
					console.log("监听失败，原因如下")
		      console.error(err);
		    },
		  });
		},
		getCharacteristics() {
		  uni.getBLEDeviceCharacteristics({
		    deviceId: this.deviceId, // 设备ID，在【4】里获取到
		    serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
		    success: (res) => {
		      this.characteristicIdList = res.characteristics;
		      for (let i = 0; i < this.characteristicIdList.length; i++) {
		        // console.log(this.characteristicIdList[i])
		        if (this.characteristicIdList[i].properties.notify) {
		          this.characteristicId = this.characteristicIdList[i].uuid;
		          this.notifyId = this.characteristicIdList[i].uuid;
		          console.log(this.notifyId);
		          this.notifyDevice(this.notifyId);
		          console.log("获取特征值成功且赋值成功");
		          break;
		        }
		      }
		    },
		    fail: (err)=> {
		      console.error("获取特征值失败");
		      console.error(err);
		    },
		  });
		},
		// 检查血压的连接
		check(str){
		    if(str.substring(0,8) == "d0c204cb") {
		        console.log("测量中")
		    }
		    if(str.substring(0,8) == "d0c20ccc"){
		        console.log("测量成功")
						this.valueList = this.hexToDecimal(str);
		        console.log(this.valueList)
		    }
		},
		getTime() {
			// 创建一个新的日期对象
			var now = new Date();
			
			// 获取年份
			var year = now.getFullYear();
			
			// 获取月份（0-11）
			var month = now.getMonth() + 1;
			
			// 获取日期
			var date = now.getDate();
			
			// 获取小时
			var hours = now.getHours();
			
			// 获取分钟
			var minutes = now.getMinutes();
			
			// 获取秒钟
			var seconds = now.getSeconds();
			
			// 格式化输出时间
			var formattedTime = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
			
			// 在控制台打印时间
			console.log(formattedTime);

		},
    listenValueChange() {
			console.log("监听中...")
			this.getTime()
      uni.onBLECharacteristicValueChange((res) => {
        // 结果里有个value值，该值为 ArrayBuffer 类型，所以在控制台无法用肉眼观察到，必须将该值转换为16进制
         let resHex = this.ab2hex(res.value);
         // console.log(resHex);
				 this.check(resHex);
      });
    },
		closeConnection() {
			console.log("正在断开连接")
			this.getTime()
			uni.closeBLEConnection({
			  deviceId : this.deviceId,
			  success: (res)=>{
			    console.log(res)
					console.log("断开连接成功")
			  },
				fail: (err) => {
					console.log(err)
					console.log("断开连接失败")
				}
			})
		},
    ab2hex(buffer) {
      const hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ("00" + bit.toString(16)).slice(-2);
        }
      );
      return hexArr.join("");
    },
		hexToDecimal(hexString) {
		  const decimalList = [];
		  for (let i = 2; i < hexString.length; i += 2) {
		    const hexValue = hexString.substring(i, i + 2);
		    const decimalValue = parseInt(hexValue, 16);
		    decimalList.push(decimalValue);
		  }
		  return decimalList;
		}
  },
};
</script>

<style>
.interface {
  flex-wrap: wrap;
  width: 315px;
  height: 136px;
  background: #ffffff;
  box-shadow: 4px 4px 4px #94d6e2;
  border-radius: 15px;
}
</style>